// axios封装
import axios from 'axios'
import 'element-plus/theme-chalk/el-message.css'
import { ElMessage } from 'element-plus';
import { useUserInfoStore } from '@/stores/userInfo';
import router from '@/router';

// 创建请求
const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 5000
})

// 拦截器
// axios请求拦截器
httpInstance.interceptors.request.use(config => {
    // 判断是否有token
    const userInfoStore = useUserInfoStore()
    const token = userInfoStore.userInfo?.token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(res => res?.data, e => {
    // 统一错误提示
    ElMessage({
        type: 'warning',
        message: e.response?.data.msg || '请求失败，请稍后再试'
    })

    // 处理401token失效错误
    const userInfoStore = useUserInfoStore()
    console.log(e.response?.status)
    if (e.response.status === 401) {
        userInfoStore.clearUserInfo()
        router.replace({ path: '/login' })
    }

    return Promise.reject(e)
})

export default httpInstance